# -*- coding: utf-8 -*-

import unittest
import sys
import os
import time
import logging

from dataclasses import dataclass
from typing import Optional
import configparser
from ast import literal_eval
from functools import reduce

# 添加执行环境
file_exec_path = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
sys.path.insert(0, file_exec_path)
from framework_strategy.gopy.trader.engine import LogEngine, EmailEngine, MainEngine, EventEngine  # NOQA
from framework_strategy.gopy.main.engine import EventEngine, Event  # NOQA
from framework_strategy.gopy.base.constant import EVENT_LOG  # NOQA
from framework_strategy.gopy.utils.file import log_path, file_exist  # NOQA
from framework_strategy.gopy import settings   # NOQA


@dataclass
class LogMsg:
    level: Optional[str]
    msg: Optional[str]



def init():
    eeg = EventEngine()
    mg = MainEngine(eeg)

    logengine = LogEngine(mg, eeg)
    return logengine, eeg

def init_msg(level: int, msg: str):
    log = LogMsg(level, msg)
    log_event = Event(EVENT_LOG, log)
    return log_event


# 测试日志的打印
class TestLogEvent(unittest.TestCase):

    @unittest.skip
    def test_init(self):

        log, eeg = init()
        # log.start()
        # eeg.start()
        print("[*] 启动事件驱动成功")

        log_event = init_msg(logging.ERROR, "测试日志")
        eeg.put(log_event)

        # -------------------------------------
        # eeg.handle_event(log.process_log_event, log_event)
        # -------------------------------------

        time.sleep(3)
        # log.stop()
        eeg.stop()
        
        print("[*] 退出")
        # return

    # @unittest.skip
    def test_print(self):

        log, eeg = init()

        log_event = init_msg(20, "oooooooo")
        log.process_log_event(log_event)

    @unittest.skip
    def test_log(self):

        log_file = log_path(LogEngine.LOGCONFIG)
        cp = configparser.RawConfigParser()

        if hasattr(log_file, 'readline'):
            cp.read_file(log_file)
        else:
            cp.read(log_file)

        change = "handler_rootHandler"
        origin = literal_eval(cp[change]["args"])

        value = reduce(lambda x, y : x + y  , ((os.path.join(settings.SETTINGS["log.path"], file),) for file in origin))
        cp[change]["args"] = repr(value)

        logging.config.fileConfig(cp)
        # LogEngine()
        





if __name__ == "__main__":
    unittest.main()
    pass